package net.ezsteam.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import net.ezsteam.EzSteam_StoreVisit_Activity;
import net.ezsteam.R;
import net.ezsteam.cons.EzSteam_Urls;
import net.ezsteam.service.EzSteam_GetCars_Service.MyAdapter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class EzSteam_GetCars_WithRemove_Service extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	private MyAdapter myAdapter;
	
	private boolean exeption = false;
	
	private ListView listview;
	
	//List<String> list;
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;

	JSONArray jArray;
	
	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = ""; 
	List<NameValuePair> params;
	HttpParams httpParameters = new BasicHttpParams();
	
	String[] arrMake;
	String[] arrModel;
	String[] arrYear;
	
	String[] arrID;

	String cusid;
	
	public EzSteam_GetCars_WithRemove_Service(Activity activity,ListView listview,String cusid) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.listview = listview;
		
		this.cusid = cusid;
		
		Button addmore = (Button)activity.findViewById(R.id.btn_Add_More);
	        addmore.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					addNewCar();
				}
		});
		
	}

	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Profile", "Loading Profile, Please Wait",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {

		try {
			
			HttpClient httpclient = new DefaultHttpClient();
		    HttpResponse response = httpclient.execute(new HttpGet(urls[0]));
		    
			HttpEntity httpEntity = response.getEntity();

			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				exeption = true;
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IOException e) {   
				exeption = true;
				e.printStackTrace();
			} catch (IllegalStateException e) {
				exeption = true;
				e.printStackTrace();
			} catch (Exception e) {
				exeption = true;
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				exeption = true;
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
		 return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		Log.d("Post Exec", "POST EXEC");
		
		Log.d("Post tt", result);
		progdialod.dismiss();

		
		Log.d("Post Exec", result); //"result" is the token *if not null
		
		
			if(!exeption){
				
				try {

					JSONObject jsonobj = new JSONObject(result);
					JSONArray service_type = jsonobj.getJSONArray("car_deatils");

					arrMake = new String[service_type.length()];
					arrModel = new String[service_type.length()];
					arrYear = new String[service_type.length()];
					arrID = new String[service_type.length()];
					
					for(int typei=0;typei<service_type.length();typei++){
						if(service_type.get(typei) instanceof JSONObject){
							JSONObject jsonDetails = service_type.getJSONObject(typei);
							arrMake[typei] = jsonDetails.getString("make");
							arrModel[typei] = jsonDetails.getString("model");
							arrYear[typei] = jsonDetails.getString("year");
							arrID[typei] = jsonDetails.getString("id");
							//list.add(""+jsonDetails.getString("reserve_time")+" "+jsonDetails.getString("type")+" "+jsonDetails.getString("location_address")+" "+jsonDetails.getString("contact_phone")+" "+jsonDetails.getString("status"));
						}
					}

					if(arrMake.length != 0){

					    myAdapter = new MyAdapter(activity,arrayListArray(arrMake));

				        listview.setAdapter(myAdapter);
					}
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				
				
				
			
			}else{
				Toast toast = Toast.makeText(activity, "Failed !!", Toast.LENGTH_SHORT);
				toast.show();
			}

	}
	
	public class MyAdapter extends ArrayAdapter<String> {

		private LayoutInflater mInflater;

		public MyAdapter(Context context, List<String> objects) {
			super(context, R.layout.ezsteam_vehicle_row, objects);
		
			mInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		 @Override
	        public int getCount() {
	            return arrMake.length;
	        }
	 
	        @Override
	        public String getItem(int position) {
	            return arrMake[position];
	        }
	 
	        @Override
	        public long getItemId(int position) {
	            return position;
	        }
	 
	        @Override
	        public View getView(final int position, View convertView, ViewGroup parent) {
	        	//convertView = mInflater.inflate(R.layout.ezsteam_appoinment_row, null);
	            View retval = LayoutInflater.from(activity).inflate(R.layout.ezsteam_vehicle_row_withupdate, null);
	            final EditText txt_data_make = (EditText) retval.findViewById(R.id.txt_make);
	            final EditText txt_data_model = (EditText) retval.findViewById(R.id.txt_model);
	            final EditText txt_data_year = (EditText) retval.findViewById(R.id.txt_year);
	            Button btnremove = (Button) retval.findViewById(R.id.btn_remove);
	            Button btnupdate = (Button) retval.findViewById(R.id.btn_update);
	            
	            btnremove.setTag(position);
	            btnupdate.setTag(position);
	            
	            btnremove.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Log.i("Remove Car", ""+position);
						
						DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
							
							
							@Override
						    public void onClick(DialogInterface dialog, int which) {
						        switch (which){
						        case DialogInterface.BUTTON_POSITIVE:

						        	EzSteam_Delete_OneCar addcar = new EzSteam_Delete_OneCar(activity,arrID[position]);
									addcar.execute(EzSteam_Urls.DeleteCar_Service);

									arrMake = removeFromPositionCar(arrMake,position);
									arrModel = removeFromPositionCar(arrModel,position);
									arrYear = removeFromPositionCar(arrYear,position);
									//myAdapter.remove(myAdapter.getItem(position));
									notifyDataSetChanged();
									
						            break;

						        case DialogInterface.BUTTON_NEGATIVE:
						            break;
						        }
						    }
							
							
						};

						AlertDialog.Builder builder = new AlertDialog.Builder(activity);
						builder.setMessage("Confirm To Delete ?").setPositiveButton("Yes", dialogClickListener)
						    .setNegativeButton("No", dialogClickListener).show();
						
							
						
					}
				});
	            
	            btnupdate.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Log.i("Update Car", ""+position);
						
						updateCar(arrID[position],arrMake[position],arrModel[position],arrYear[position]);
						
						arrMake[position] = txt_data_make.getText().toString().trim();
						arrModel[position] = txt_data_model.getText().toString().trim();
						arrYear[position] = txt_data_year.getText().toString().trim();
						//myAdapter.remove(myAdapter.getItem(position));
						notifyDataSetChanged();
					}
				});
	            
	            txt_data_make.setText(arrMake[position]);
	            txt_data_model.setText(arrModel[position]);
	            txt_data_year.setText(arrYear[position]);
	            
	            return retval;
	        }
	}

	private String[] addCar(String[] array, String object){
		  ArrayList<String> lst = new ArrayList<String>();
		  for (String o : array){
		    lst.add(o);
		  }
		  lst.add(object);
		  return lst.toArray(new String[lst.size()]);
	}
	
	private String[] removeFromPositionCar(String[] array, int position){
		List<String> numlist = new ArrayList<String>();
		for(int i= 0;i<array.length;i++)
		{
		 if(i == position)
		 {
		   // No operation here 
		 }
		 else
		 {
		     numlist.add(array[i]);
		 }
		}
		array = numlist .toArray(new String[numlist .size()]);
		
		return array;
	}
	
	private List<String> arrayListArray(String[] array){
		List<String> numlist = new ArrayList<String>();
		for(int i= 0;i<array.length;i++)
		{
		   numlist.add(array[i]);
		}
		return numlist;
	}

	
	private void addNewCar(){
		final Dialog dialog = new Dialog(activity);

		dialog.setContentView(R.layout.ezsteam_vehicle_row);
		dialog.setTitle("Add New Car");

		final EditText txtMake = (EditText)dialog.findViewById(R.id.txt_make);
		final EditText txtModel = (EditText)dialog.findViewById(R.id.txt_model);
		final EditText txtYear = (EditText)dialog.findViewById(R.id.txt_year);
		
		Button btndone = (Button)dialog.findViewById(R.id.btn_remove);
		
		btndone.setText("Add car");
		
		btndone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(!txtMake.getText().toString().trim().equals("")||!txtModel.getText().toString().trim().equals("")||!txtYear.getText().toString().trim().equals("")){
					
					EzSteam_Add_OneCar addcar = new EzSteam_Add_OneCar(activity,cusid,txtYear.getText().toString(),txtMake.getText().toString(),txtModel.getText().toString());
					addcar.execute(EzSteam_Urls.AddCar_Service);
					
					/*arrMake = addCar(arrMake,txtMake.getText().toString().trim());
					arrModel = addCar(arrModel,txtModel.getText().toString().trim());
					arrYear = addCar(arrYear,txtYear.getText().toString().trim());
					myAdapter.notifyDataSetChanged();*/
					
					dialog.dismiss();
					
				}else{
					Toast toast = Toast.makeText(activity, "No Valid Data !!", Toast.LENGTH_SHORT);
					toast.show();
				}
				
				
			}
		});
		
		dialog.show();
	}
	
	private void updateCar(final String carid,final String make,final String model,final String year){
		final Dialog dialog = new Dialog(activity);

		dialog.setContentView(R.layout.ezsteam_vehicle_row);
		dialog.setTitle("Update Car");

		final EditText txtMake = (EditText)dialog.findViewById(R.id.txt_make);
		final EditText txtModel = (EditText)dialog.findViewById(R.id.txt_model);
		final EditText txtYear = (EditText)dialog.findViewById(R.id.txt_year);
		
		txtMake.setText(make);
		txtModel.setText(model);
		txtYear.setText(year);
		
		Button btndone = (Button)dialog.findViewById(R.id.btn_remove);
		
		btndone.setText("Update car");
		
		btndone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(!txtMake.getText().toString().trim().equals("")||!txtModel.getText().toString().trim().equals("")||!txtYear.getText().toString().trim().equals("")){
					EzSteam_Update_OneCar addcar = new EzSteam_Update_OneCar(activity,carid,txtYear.getText().toString(),txtMake.getText().toString(),txtModel.getText().toString());
					addcar.execute(EzSteam_Urls.UpdateCar_Service);
				}else{
					Toast toast = Toast.makeText(activity, "No Valid Data !!", Toast.LENGTH_SHORT);
					toast.show();
				}
				
				dialog.dismiss();
			}
		});
		
		dialog.show();
	}
	
	private void deleteCar(final String carid){

		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			
			
			@Override
		    public void onClick(DialogInterface dialog, int which) {
		        switch (which){
		        case DialogInterface.BUTTON_POSITIVE:

		        	EzSteam_Delete_OneCar addcar = new EzSteam_Delete_OneCar(activity,carid);
					addcar.execute(EzSteam_Urls.DeleteCar_Service);

		            break;

		        case DialogInterface.BUTTON_NEGATIVE:
		            break;
		        }
		    }
			
			
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setMessage("Confirm To Delete ?").setPositiveButton("Yes", dialogClickListener)
		    .setNegativeButton("No", dialogClickListener).show();

	}

}
